package com.shopManager.contoller.auth;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.shopManager.utils.RedisCacheUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.shopAuth.bean.Admin;
import com.shopAuth.feign.AdminFeign;

import shopBean.common.bean.RestResult;
import shopBean.common.responseCode.Status;
@Controller
@RefreshScope
public class LoginContoller {
	private static final Logger log = LoggerFactory.getLogger(LoginContoller.class);
	@Autowired
	RedisCacheUtils redisCacheUtils;
	@Value("${redis-service}")
	private String fileurl;
	@Autowired
	RedisTemplate<String,String> redisTemplate;
	@Autowired
	AdminFeign adminFeign;
	
	@RequestMapping("/index.shtml")
	public String index(String msg,ModelMap map){
		
		map.put("msg", msg);
		return "index";
	}
	@ResponseBody
	@RequestMapping("/test1.do")
	public String test1(){
		return fileurl;
	}
	@ResponseBody
	@RequestMapping("/test.do")
	public String tesst(){
		log.debug("1111{}",1111);
		redisTemplate.opsForValue().set("test", UUID.randomUUID().toString());
		log.debug("result{}",1111);
		return redisCacheUtils.getRedisFeign().opsForValueGet("test");
	}
	@RequestMapping("/login.do")
	public String login(){
		
		return "login";
	}
	
	@RequestMapping("/loginAction.do")
	public String loginAction(String user,String password,RedirectAttributes model,HttpServletRequest request){
		if(StringUtils.isEmpty(user)||StringUtils.isEmpty(password)){
			model.addAttribute("msg", "账号密码不能为空");
			return "redirect:login.do";
		}
		RestResult result = adminFeign.login(password, user);
		log.debug("result:"+result);
		if(result== null) {
			model.addFlashAttribute("msg", "登录失败，服务不可用");
			return "redirect:login.do";
		}else if(StringUtils.equals(result.getStatusCode(), Status.sys_success)){
			Admin admin = new Admin();
			admin.setUser(user);
			admin.setPassword(password);
			request.getSession().setAttribute("user", admin);
			return "redirect:index.shtml";
		}else {
			model.addFlashAttribute("msg", result.getMsg());
			return "redirect:login.do";
		}

	}
	@ResponseBody
	@RequestMapping("getSession.do")
	public Object getSession(HttpServletRequest request) {
		return request.getSession().getAttribute("user");
	}
}
